package com.tianquan.log;/**
 * @author starsea
 * @date 2024-10-19 下午12:52
 */

import java.io.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.log
 * @Author: tianquan
 * @CreateTime: 2024-10-19  12:52
 * @Description: 将日志持久化本地
 * @Version: 1.0
 */

public class LocalLogService  {

    private String fileName;

    public LocalLogService(String fileName) {
        this.fileName = fileName;
    }

    public void LocalPersistence(List<Log> list) {
        File file = new File(fileName);
        // 文件不存在就创建文件夹
        if (!file.exists()) {
            try {
                file.mkdirs();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        // 文件夹存在就写入文件 找到今天的日志文件
        // 获取到当前年月日
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        int day = now.getDayOfMonth();
        String logName = year + "-" + month + "-" + day + ".log";

        File todayFile = new File(file, logName);
        // 文件不存在就创建
        if (!todayFile.exists()) {
            try {
                todayFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        BufferedWriter writer = null;
        try {
            // 然后追加写入文件
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(todayFile, true)));
            for (Log log : list) {
                writer.write(log.toString());
                writer.newLine();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
